package gazzera.node.core.peer;

import gazzera.node.core.*;
import gazzera.node.core.events.*;
import gazzera.node.core.messages.*;

import java.net.*;


class DataPump implements Runnable
{
	Peer peer;
	DataPumpSource src;
	private ICore core;

	public DataPump(Peer peer, DataPumpSource src, ICore core)
	{
		this.src = src;
		this.peer = peer;
		this.core = core;
	}

	@Override
	public void run()
	{
		boolean interrupted = false;
		try
		{
			src.init();

			Message msg;
			while ((msg = src.next()) != null)
			{
				peer.send(msg);
			}
		}
		catch (SocketException e)
		{
			interrupted = true;
		}
		catch (Exception e)
		{
			e.printStackTrace();
			interrupted = true;
		}
		try
		{
			src.finished(interrupted);
		}
		catch (Exception e)
		{
			core.logErr(e);
		}
		
		
		core.enqueue(new DataPumpTerminated(peer, src, interrupted));
		
	}
}
